﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Camera
{
    class Program
    {
        static void Main(string[] args)
        {
            
        }



        private static byte[] _request;
        private static bool _keepRunning;
        private static bool _isRunning;

        static void GetCameraFrame()
        {
            _request = Encoding.ASCII.GetBytes(
@"GET /cgi-bin/cmd/system?GET_STREAM HTTP/1.1 
Cache-Control: no-cache 
Connection: Keep-Alive 
Pragma: no-cache 
Authorization: Basic QWRtaW46MTIzNDU2 
Host: 172.16.3.79 
User-Agent: AHTTP

");
            var thread = new Thread(ReceiveData) { IsBackground = true };
            thread.Start();
            while (true)
            {
                var command = Console.ReadLine();
                if (string.IsNullOrEmpty(command)) continue;
                if (command == "exit") break;
            }
            _keepRunning = false;
            while (_isRunning)
            {
                Console.Write(".");
            }
        }
        static void ReceiveData()
        {
            _isRunning = true;
            _keepRunning = true;
            var buffer = new byte[0xFFFFFF];
            using (var file = new FileStream(@"C:\97.raw", FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
            {
                var socket = new Socket(
                    AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);
                try
                {
                    socket.Connect("172.16.18.102", 80);
                    socket.Send(_request);
                    while (_keepRunning)
                    {
                        var len = socket.Receive(buffer);
                        if (len < 1) continue;

                        file.Write(buffer, 0, len);
                        file.Flush();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                _isRunning = false;
            }
            
        }
    }
}
